import { useEffect, useState } from "react";

const useWebSocket = (path) => {

    const [webSocket, setWebSocket] = useState(null);
    const [socketRes, setSocketRes] = useState({});

    useEffect(() => {
        if (!window.WebSocket) {
            return;
        }

        init(path);
    }, [path]);

    function init(url) { 
        const ws = new WebSocket(url);

        setWebSocket(ws);

        ws.onopen = function() { 
            // console.log("建立webSocket连接", evt); 
            // ws.send("Hello WebSockets!");
        };

        ws.onmessage = function(evt) {
            // console.log("接受到webSocket消息: " + evt.data);
            const data = JSON.parse(evt.data);
            setSocketRes(data);
            // ws.close();  // 关闭webSocket连接
        };

        ws.onclose = function() {
            // console.log("关闭webSocket连接", evt);
        };    
    }

    return [webSocket, socketRes];
};

export default useWebSocket;